import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:spring_fairy/api/diary_api.dart';
import 'package:spring_fairy/api/user_store.dart';
import 'package:spring_fairy/model/mood_diary.dart';
import 'package:spring_fairy/model/store.dart';

class DiaryEditorPage extends StatefulWidget {
  const DiaryEditorPage({super.key});

  @override
  State<DiaryEditorPage> createState() => _DiaryEditorPageState();
}

class _DiaryEditorPageState extends State<DiaryEditorPage> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();

  final DateTime _now = DateTime.now();
  String _selectedMood = '😊';

  final List<String> moods = ['😊', '😢', '😡', '😌', '🤔', '😴'];
  final DiaryAPI _diaryAPI = DiaryAPI();
  MoodDiary? diary;

  @override
  void initState() {
    super.initState();
    diary = Store.currentMoodDiary;

    _selectedMood = diary != null ? diary!.moodSummary ?? '😊' : '😊';
    _titleController.text = diary != null ? diary!.title ?? '' : '';
    _contentController.text = diary != null ? diary!.content ?? '' : '';
  }

  void _saveDiary() {
    final title = _titleController.text.trim();
    final content = _contentController.text.trim();
    final date = DateFormat('yyyy-MM-dd HH:mm').format(_now);

    if (content.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('正文不能为空')),
      );
      return;
    }

    if(diary == null) {
       diary = MoodDiary(
          userId: UserStore.user!.id,
          trackId: Store.currentMoodTrack!.id,
          diaryDate: DateTime.now(),
          title: title,
          content: content,
          moodSummary: _selectedMood,
          createdAt: DateTime.now()
      );
       _diaryAPI.writeDiary(diary!);
    } else {
      diary = MoodDiary(
        diaryDate: DateTime.now(),
        title: title,
        content: content,
        moodSummary: _selectedMood
      );
      _diaryAPI.update(diary!);
    }

    Store.currentMoodDiary = diary;

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('日记已保存')),
    );

    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    final dateStr = DateFormat('yyyy-MM-dd HH:mm').format(_now);

    return Scaffold(
      appBar: AppBar(
        title: const Text('MoodDiary'),
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: _saveDiary,
            tooltip: '保存',
          )
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('📅 $dateStr'),
            const SizedBox(height: 8),
            Row(
              children: [
                const Text('心情：', style: TextStyle(fontSize: 16)),
                ...moods.map((mood) {
                  return GestureDetector(
                    onTap: () => setState(() => _selectedMood = mood),
                    child: Container(
                      margin: const EdgeInsets.symmetric(horizontal: 4),
                      padding: const EdgeInsets.all(4),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _selectedMood == mood
                            ? Colors.blue.shade100
                            : Colors.transparent,
                      ),
                      child: Text(
                        mood,
                        style: const TextStyle(fontSize: 22),
                      ),
                    ),
                  );
                }).toList(),
              ],
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _titleController,
              decoration: const InputDecoration(
                labelText: '标题',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: TextField(
                controller: _contentController,
                decoration: const InputDecoration(
                  labelText: '正文',
                  border: OutlineInputBorder(),
                  alignLabelWithHint: true,
                ),
                maxLines: null,
                expands: true,
                textAlignVertical: TextAlignVertical.top,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
